<template>
	<view class="container">
		<!-- <u-navbar title="我的" bgColor="rgba(255,255,255,0)" leftIconColor="#000" titleStyle="color:#000;font-weight: bold;"></u-navbar> -->
		<image class="bgImg" src="../../static/images/my_top.png" mode=""></image>
		<u-navbar
			title="我的" 
			:isBack="false"
			:background="{ background: 'rgba(0,0,0,0)' }" 
			:titleColor="'#fff'"
		></u-navbar>
		<z-paging
			ref="paging"
			v-model="recommendList"
			@query="getRecommendList" 
			auto-show-back-to-top 
			:empty-view-text="emptyText" 
			:empty-view-img="emptyImg" 
		>
			<template v-slot:top>
				<view :style="{'margin-top': sHeight}"></view>
			</template>
			<!-- 顶部背景图 -->
			<view class="content">
				<view class="content_1">
					<view 
						class="left flex justify-btw align-start" 
						@tap="mainStore.userInfo.id ? '' : ToLoginPage()"
					>
						<image :src="mainStore.userInfo.avatar || '/static/images/null_avatar.jpg'" mode=""></image>
						<view class="userInfo flex flex-column justify-center">
							<text v-if="mainStore.userInfo.nickname" class="userInfo_nickname">{{ mainStore.userInfo.nickname }}</text>
							<text v-else class="userInfo_clickLogin">点击登录</text>
							<text class="userInfo_phone" v-if="mainStore.userInfo.mobile">{{ mainStore.userInfo.mobile }}</text>
						</view>
					</view>
					<view class="right flex align-start"> 
						<image @tap.stop="ToUserInfo" src="../../static/images/edit_icon.png" mode=""></image>
					</view>
				</view>
				<view class="content_2 flex justify-btw align-end" style="align-items: flex-end;">
					<view class="left flex align-center">
						<text>钱包余额：</text>
						<text>{{ mainStore.userInfo.balance||mainStore.userInfo.balance==0 ? mainStore.userInfo.balance : '--'}}</text>
					</view>
					<view class="right">
						<view 
							v-if="currentToken && !proxy.utils.isHide()"
							class="moneyBtn flex justify-center align-center"
							@tap.stop="ToMyWallet()"
						>申请提现</view>
					</view>
				</view>
				<!-- 菜单区 -->
				<view class="content_3 flex flex_clm justify-start">
					<!-- 菜单项 -->
					<view 
						class="flex justify-btw align-center" 
						v-for="item in menuList" 
						:key="item.id"
						v-show="item.isShow"
						@tap.stop="handleClickMenuItem(item.id)"
					>
						<view class="flex justify-start align-center">
							<image style="width: 60rpx;height: 60rpx;" :src="item.image" mode=""></image>
							<text style="margin-left: 22rpx;">{{ item.text }}</text>
						</view>
						<image style="width: 22rpx;height: 30rpx;" src="@/static/images/icon_list_next.png" mode=""></image>
					</view>
				</view>
				<view 
					style="margin-top: 120rpx;width: 100%;"
					v-if="currentToken"
				>
					<u-button class="logoutBtn" @click.stop="showLogout = true">退出登录</u-button> 
				</view>
			</view>
		</z-paging>
		<!-- 登录弹框 -->
		<u-popup 
			v-model="showLogin" 
			mode="bottom" 
			border-radius="25" 
			@close="handleCancel()"
		>
			<view style="padding: 40rpx 30rpx;min-width: 300rpx;">
				<h2 style="font-weight: bold;">申请获取您的头像、昵称</h2>
				<u-form :model="queryParams" ref="form1">
					<u-form-item label="头像:" prop="avatar">
						<view style="width: 100%;" class="flex justify-end">
							<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-wrapper">
								<image :src="queryParams.avatar" mode=""
									style="width: 60rpx;height: 60rpx;border-radius: 10rpx;background-color: #eee;">
								</image>
							</button>
						</view>
					</u-form-item>
					<u-form-item label="昵称:" prop="nickname">
						<u-input 
							v-model="queryParams.nickname"
							type="nickname" 
							input-align="right" 
							placeholder="请输入" 
							@blur="(e)=>{ queryParams.nickname = e }"
						/>
					</u-form-item>
				</u-form>
				<view class="flex justify-around" style="margin-top: 40rpx;">
					<u-button type="default" size="medium" @click.stop="handleCancel()">关闭</u-button>
					<u-button 
						type="success" 
						size="medium" 
						open-type="getPhoneNumber" 
						@getphonenumber="getPhoneNumber"
					>允许</u-button>
				</view>
			</view>
		</u-popup>
		<!-- 退出登录弹框 -->
		<u-popup 
			v-model="showLogout" 
			class="logoutDialog"
			mode="bottom" 
			border-radius="25" 
			:mask-close-able="true"
		>
			<view style="padding: 20rpx 20rpx;">
				<view class="logoutClass"><text>是否确定退出登录</text></view>
				<view 
					class="logoutClass" 
					style="color: #3B8CDC;margin-top: 20rpx;" 
					@click.stop="handleLogout()"
				><text>确定</text></view>
			</view>
		</u-popup>
		
		<u-modal
			v-model="conShow" 
			content="确认打开客服会话？" 
			@confirm="openCustomLink()"
			:show-cancel-button="true"
			confirmText="确认"
			cancelText="取消"
		></u-modal>
	</view>
</template>

<script setup>
import { getCurrentInstance, onMounted, ref, computed } from 'vue';
import { uploadFile } from '@/utils/uploadFile.js';
import { onLoad, onUnload, onShow, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app"
import {useMainStore} from '@/store/index.js'
	const mainStore = useMainStore()
	const {proxy} = getCurrentInstance()
	const showLogin = ref(false)
	const showLogout = ref(false)
	const sHeight = ref('')
	const conShow = ref(false)
	const queryParams = ref({
		avatar: '/static/images/null_avatar.jpg',
		nickname: '',
		encryptedData: '',
		iv: '',
		sessionKey:'',
		openid:'',
	})
	const link = ref('')
	const menuList = computed(()=>[
		{
			id:1, 
			image:'/static/images/apply.png', 
			text: mainStore.userInfo.isPartner==2 ? '已成为合伙人' : '申请成为合伙人',
			isShow: true,
		},
		{id:2, image:'/static/images/invite.png', text:'我的邀请', isShow: true},
		{id:3, image:'/static/images/agreement.png', text:'平台协议', isShow: true},
		{id:4, image:'/static/images/kf.png', text:'联系客服', isShow: true},
		{id:5, image:'/static/images/setting.png', text:'设置', isShow: true},
	])
	const currentToken = ref('')
	
	
	
	// 自定义此页面的转发给好友(已经有全局的分享方法，此处会覆盖全局)
	onShareAppMessage(()=>{
			return {
				title: '设计很忙',
				// path: '/pagesA/washBeauty/MaintenanceDetail?id=' + this.options.id + '&back=' + 1 + '&storeId=' + this.options.storeId,
				// query: `id=${this.options.id}&storeId=${this.options.storeId}&back=1`,
				// imageUrl: this.Detail.goodsLogo
			};
		
	})
	// 自定义页面的分享到朋友圈
	onShareTimeline(()=>{
		return {
			title: '设计很忙',
			// query: `id=${this.options.id}&title=${this.options.title}&status=${this.options.status}&currentTimeFlag=${this.options.currentTimeFlag}&back=1`,
			// imageUrl: this.list[0]
		};
	})
	
	
	
	
	onShow(()=>{
		mainStore.handleGetUserInfo()
		setTimeout(()=>{
			currentToken.value = uni.getStorageSync('TOKEN')
		}, 300)
	})
	onLoad(()=>{
		getStatusHeight() //适配顶部高度
		getLink()
		uni.$on('handle_apply', data=>{
			setTimeout(()=>{
				proxy.tui.toast('申请成功，待管理员审核')
			}, 800)
		})
		uni.$on('handle_tixian', data=>{
			setTimeout(()=>{
				proxy.tui.toast('提现正在审核中')
			}, 800)
		})
	})
	onUnload(()=>{
		uni.$off('handle_apply')
		uni.$off('handle_tixian')
	})
	// 获取客服链接
	function getLink(){
		proxy.api.system({code:'kf_link'}).then(res=>{
			link.value = res?.data?.data.find(item=>item.code=='contact_link')?.dictValue
		})
	}
	function getStatusHeight() {
		sHeight.value = uni.getSystemInfoSync().statusBarHeight + 54 + 'px';
	}
	// 跳转到我的钱包
	function ToMyWallet(){
		uni.navigateTo({
			url:`/pages/my/myWallet`
		})
	}
	// 跳转到个人信息
	function ToUserInfo(){
		uni.navigateTo({
			url:`/pages/setting/userInfo`
		})
	}
	// 调登录接口
	function loginApi(query){
		proxy.api.login(query).then(res=>{
			proxy.tui.toast('登录成功'+res.data.data)
			// 设置token
			uni.setStorageSync('TOKEN', res.data.data.token)
			currentToken.value = res.data.data.token
			// 获取用户信息
			mainStore.handleGetUserInfo()
		})
	}
	// 跳转到登录页面
	function ToLoginPage(){
		uni.navigateTo({
			url: '/pages/my/login'
		})
	}
	// 直接登录 or 弹框注册后登录
	function ToLogin(){
		uni.login({
			provider: 'weixin',
			success: res => {
				// 通过code调用获取openid接口 查询是否已注册
				// 如果已注册，直接获取用户信息
				proxy.api.getWxOpenId({code: res.code}).then(res => {
					let resData = res.data.data
					//已注册 
					if(resData.isTrue==1){  
						let query = {
							openid: resData.user ?. wechatAppletOpenid,
							type: '5',
							userType: '1',
						}
						loginApi(query)
					}else if(resData.isTrue==0){  
						queryParams.value.openid = resData.openid
						showLogin.value = true
					}else {
						proxy.tui.toast('返回数据有误，请重试')
					}
				})
			},
			fail: err=>{
				console.log('err', err)
			}
		});
		
	}
	// 退出登录
	function handleLogout(){
		uni.removeStorageSync('TOKEN')
		uni.removeStorageSync('USER_INFO')
		mainStore.userInfo = {}
		currentToken.value = ''
		showLogout.value = false
		proxy.tui.toast('退出登录成功')
	}
	// 上传图片
	// function uploadImg() {
	// 	uni.chooseImage({
	// 		count: 1,
	// 		sizeType: ['original', 'compressed'],
	// 		sourceType: ['album'],
	// 		success: res => {
	// 			let Imgsrc = res.tempFilePaths[0];
	// 			let sux = res.tempFiles[0].name;
	// 			return new Promise((resolve, reject) => {
	// 				uni.showLoading({
	// 					title: '加载中'
	// 				});
	// 				uploadFile(Imgsrc, 'image/', sux).then(result => {
	// 					// this.model.collectionCode = result;
	// 					console.log('url', result)
	// 					uni.hideLoading();
	// 				}).catch(err => {
	// 					proxy.tui.toast('图片上传失败!请重新上传');
	// 				});
	// 			});
	// 		}
	// 	});
	// }
	// 获取用户头像
	function onChooseAvatar(e) {
		uploadFile({
			filePath: e.detail.avatarUrl,
			dir: 'image/',
			name: 'avatar'
		}).then(result => {
			queryParams.value.avatar = result
		}).catch(err => {
			console.log('werr',err)
			proxy.tui.toast('图片上传失败!请重新上传');
		});
		// queryParams.value.avatar = e.detail.avatarUrl
	}
	// 关闭登录弹框
	function handleCancel(){
		showLogin.value = false
		showLogout.value = false
		queryParams.value = {
			avatar: '/static/images/null_avatar.jpg',
			nickname: '',
			encryptedData: '',
			iv: '',
			sessionKey:'',
			openid: '',
		}
	}
	
	function openCustomLink(){
		if(proxy.utils.isLogin()){
			if(!link.value){
				proxy.tui.toast('客服链接未配置')
				return
			}
			wx.openCustomerServiceChat({
				extInfo:{
					url: link.value
				},
				corpId: 'ww591e8d883d4208fd', // 如果需要的话  
				success(res) {  
				 proxy.tui.toast('客服会话已成功打开');  
				},  
				fail(err) {
					console.log(err)
				 proxy.tui.toast('打开客服会话失败');  
				}  
			}); 
		}
	}
	
	function handleClickMenuItem(id) {
		if (id == 1) {
			// 申请成为合伙人
			if(proxy.utils.isLogin()){
				uni.navigateTo({
					url:`/pages/my/apply`
				})
			}
		} else if (id == 2) {
			// 我的邀请
			if(proxy.utils.isLogin()){
				uni.navigateTo({
					url:`/pages/my/myInvitation`
				})
			}
		} else if (id == 3) {
			// 平台协议
		    console.log('点击了3菜单'); 
			uni.navigateTo({
				url:`/pages/agreement/agreement?pageTitle=平台协议&code=platform_protocol`
			})
		} else if (id == 4) {
			// 联系客服
			conShow.value = true
		} else if (id == 5) {
			// 设置
		   uni.navigateTo({
		   	url:`/pages/setting/setting`
		   })
		}
	}
	
	// 获取手机号
	function getPhoneNumber(e) {
		queryParams.value.encryptedData = e.detail.encryptedData,
		queryParams.value.iv = e.detail.iv,
		uni.login({
			provider: 'weixin',
			success: res => {
				// 通过参数获取sessionKey，然后调用登录接口注册账号
				proxy.api.initWxLogin({code: res.code}).then(res => {
					queryParams.value.sessionKey = res.data.data
					let query = {
						...queryParams.value,
						type: '5',
						userType: '1',
						invitationCode: uni.getStorageSync('SCENE'),
					}
					console.log('注册请求参数', query)
					showLogin.value = false
					// 注册登录
					loginApi(query)
				})
			},
			fail: err=>{
				console.log('err', err)
			}
		});
	}
  
  
  
  
  // function getPhoneNumber(e) {
  // 	console.log(e);
  // 	if (e.detail.errMsg == 'getPhoneNumber:ok') {
  // 		uni.login({
  // 			provider: 'weixin',
  // 			success: ss => {
  // 				const params = {
  // 					code: ss.code
  // 				};
  // 				const paramss = {
  // 					encryptedData: e.detail.encryptedData,
  // 					iv: e.detail.iv
  // 				};
  				
  // 			}
  // 		});
  // 	} else {
  // 		proxy.tui.toast('已取消');
  // 	}
  // }
</script>

<style lang="scss" scoped>
	.logoutBtn ::v-deep .u-btn--default, .u-btn--default-hover{
		background-color: $uni-color-primary !important;
		color: #fff !important;
		border-radius: 16rpx;
	}
	.logoutDialog ::v-deep .u-drawer-bottom{
		background-color: rgba(0,0,0,0) !important;
	}
	.logoutClass{
		width: 710rpx;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		@include str(30rpx, bold, #333);
		line-height: 49rpx;
		background-color: #fff;
		border-radius: 12rpx;
	}
	.bgImg {
		width: 100vw;
		height: 460rpx;
		z-index: -99;
	}

	.avatar-wrapper {
		padding: 0;
		margin: 0;
		width: 60rpx;
		height: 60rpx;
		background-color: raga(0, 0, 0, 0);
	}

	.container {
		width: 100vw;
		background-color: $uni-bg-color-grey;
		height: 100vh;
		.content {
			width: calc(100vw - 40rpx);
			margin-left: 20rpx;
			position: relative;

			.content_1,
			.content_2 {
				width: 100%;
				border-radius: 20rpx;
				margin-bottom: 20rpx;
				box-sizing: border-box;
				padding: 34rpx 36rpx;
				background-color: #fff;
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				vertical-align: bottom;
			}

			.content_1>.left {
				image {
					margin-right: 28rpx;
					width: 96rpx;
					height: 96rpx;
					border: 1px solid #ccc;
					border-radius: 50%;
				}

				.userInfo {
					height: 96rpx;
					font-family: 'PingFang SC';

					&_nickname {
						font-weight: bold;
						font-size: 36rpx;
						color: #333333;
						line-height: 50rpx;
					}
					&_clickLogin{
						font-weight: bold;
						font-size: 32rpx;
						color: #666;
						line-height: 50rpx;
					}

					&_phone {
						font-weight: 500;
						font-size: 24rpx;
						color: #666666;
						line-height: 33rpx;
					}
				}
			}

			.content_1>.right {
				image {
					width: 42rpx;
					height: 42rpx;
				}
			}

			.content_2>.left {
				&>text:first-child {
					@include str(26rpx, 400, #666);
					vertical-align: bottom;
				}

				&>text:last-child {
					@include str(35rpx, bolder, $uni-color-primary);
					vertical-align: bottom;
				}
			}

			.content_2>.right {
				.moneyBtn {
					padding: 10rpx 20rpx;
					background-color: $uni-color-primary;
					@include str(28rpx, 400, #fff);
					border-radius: 40rpx;
				}
			}
			.content_3{
				padding: 20rpx 22rpx;
				box-sizing: border-box;
				width: 100%;
				border-radius: 20rpx;
				margin: 20rpx 0;
				background-color: #fff;
				display: flex;
				text{
					@include str(32rpx, bold, #333);
				}
				&>view{
					line-height: 100rpx;
				}
			}
		}
	}
</style>